package com.example.demo.server;

import com.example.demo.pojo.DeciveData;
import com.example.demo.repository.DeviceDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Service
public class DeciveDataServer {
    private static final int UDP_PORT = 8080;
    private int ledSwitchStatus = 0; // 默认关闭
    @Autowired
    private DeviceDataRepository repository;


    public void startUDPServer() throws IOException {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
                System.out.println("UDP Server started on port " + UDP_PORT);
                byte[] buffer = new byte[1024];

                while (true) {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    socket.receive(packet); // 阻塞接收数据

                    // 解析数据包
                    String received = new String(
                            packet.getData(),
                            0,
                            packet.getLength(),
                            StandardCharsets.UTF_8
                    );
                    InetAddress clientAddress = packet.getAddress();
                    int clientPort = packet.getPort();

                    // 处理业务逻辑
                    processMessage(received, clientAddress, clientPort);
                }
            } catch (IOException e) {
                System.err.println("UDP Server error: " + e.getMessage());
            }
        }).start();
    }



    public void processMessage(String message, InetAddress address, int port) {
        // 解析传感器数据
        String[] parts = message.split(",");
        if (parts.length == 2) {

            DeciveData Data = new DeciveData();
            Data.setTemperature(Float.parseFloat(parts[0]));
            Data.setHumidity(Float.parseFloat(parts[1]));
            Data.setTimestamp(LocalDateTime.now());
            repository.save(Data);
        }

        // 构建控制响应
        String response = String.format("led_switch=%d", ledSwitchStatus);
        sendControlCommand(response, address, port);
    }

    private void sendControlCommand(String cmd, InetAddress address, int port) {
        // 发送控制指令（独立方法）
        try (DatagramSocket socket = new DatagramSocket()) {
            byte[] data = cmd.getBytes();
            DatagramPacket packet = new DatagramPacket(
                    data, data.length, address, port
            );
            socket.send(packet);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // 新增状态设置方法（供控制层调用）
    public void setLedSwitchStatus(int status) {
        this.ledSwitchStatus = (status != 0) ? 1 : 0;
    }


}
